package com.xieyong.mywebsite.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xieyong.mywebsite.mapper.CategoryMapper;
import com.xieyong.mywebsite.model.entity.Category;
import com.xieyong.mywebsite.service.CategoryService;
import com.xieyong.mywebsite.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryMapper categoryMapper;

    @Override
    public void add(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        category.setCreateId(id);
        categoryMapper.insert(category);
    }

    @Override
    public void update(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);
    }

    @Override
    public void delete(Category category) {
        Map<String, Object> stringObjectMap = ThreadLocalUtil.get();
        Integer id = (Integer) stringObjectMap.get("id");
        categoryMapper.delete(category.getId(), id, LocalDateTime.now());
    }

    @Override
    public void deleteById(Integer id) {
        Map<String, Object> stringObjectMap = ThreadLocalUtil.get();
        Integer operaid = (Integer) stringObjectMap.get("id");
        categoryMapper.delete(id, operaid, LocalDateTime.now());
    }

    @Override
    public PageInfo<Category> page(Integer pageNum, Integer pageSize, Category category) {
        PageHelper.startPage(pageNum, pageSize);
        List<Category> categories = categoryMapper.selectByCondition(category);
        return PageInfo.of(categories);
    }

    @Override
    public List<Category> list() {
        Map<String, Object> stringObjectMap = ThreadLocalUtil.get();
        Integer id = (Integer) stringObjectMap.get("id");
        return categoryMapper.list(id);
    }

    @Override
    public Category findById(Integer id) {
        return categoryMapper.selectById(id);
    }
}
